﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Text;
using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Model;
using ViewModel.admin;
using WebApp.Models;
using System.Security.Claims;
using Base;

namespace WebApp.Controllers
{
    public class AdminController : Controller
    {

        EFContext _ef;

        public AdminController(EFContext ef)
        {
            this._ef = ef;
        }

        #region 管理员

        public IActionResult List(string Name, int Page = 1, int PageSize = 20)
        {
            IQueryable<sys_admin> q = _ef.sys_admin.Where(x => 1 == 1);
            if (!string.IsNullOrEmpty(Name))
            {
                q = q.Where(x => x.admin_name.Contains(Name));
            }
            int skip = (Page - 1) * PageSize;
            //_ef.sys_admin.ToList();
            //List<sys_adminVm> list =;
            ViewBag.Name = Name;
            PagerModel pm = new PagerModel();
            pm.Page = Page;
            pm.PageSize = PageSize;
            pm.Total = q.Count();
            pm.Data = Mapper.Map<List<sys_admin>, List<sys_adminVm>>(q.Skip(skip).Take(PageSize).ToList());
            return View(pm);
        }

        [HttpPost]
        public IActionResult Delete(string ids)
        {
            try
            {
                List<int> arr = ids.Split(',').Select(x => int.Parse(x)).ToList();
                foreach (int id in arr)
                {
                    sys_admin sa = _ef.sys_admin.FirstOrDefault(x => x.id == id);
                    if (sa != null)
                    {
                        _ef.sys_admin.Remove(sa);
                    }
                }
                _ef.SaveChanges();
                return Content("success");
            }
            catch (Exception ex)
            {
                return Content(ex.Message);
            }
        }

        [HttpPost]
        public IActionResult SetState(int id, int IsEnable)
        {
            try
            {
                sys_admin sa = _ef.sys_admin.FirstOrDefault(x => x.id == id);
                if (sa != null)
                {
                    if (IsEnable == 1)
                    {
                        sa.admin_status = 1;
                    }
                    else
                    {
                        sa.admin_status = 0;
                    }
                    _ef.Update(sa);
                    _ef.SaveChanges();
                }
                return Content("success");
            }
            catch (Exception ex)
            {
                return Content(ex.Message);
            }
        }


        public IActionResult Edit(int id = 0)
        {
            sys_adminVm sa = new sys_adminVm();
            if (id != 0)
            {
                sys_admin d = _ef.sys_admin.FirstOrDefault(x => x.id == id);
                if (d != null)
                {
                    sa = Mapper.Map<sys_admin, sys_adminVm>(d);
                    sa.admin_password = "";
                }
            }
            List<sys_admin_group> gs= _ef.sys_admin_group.ToList();
            List<sys_admin_groupVm> gsv = Mapper.Map<List<sys_admin_group>,List<sys_admin_groupVm>>(gs);
            ViewBag.groups = gsv;
            return View(sa);
        }

        [HttpPost]
        public IActionResult EditAction([ModelBinder(typeof(JsonBinder<sys_adminVm>))]sys_adminVm sav)
        {
            sys_admin sa = Mapper.Map<sys_adminVm, sys_admin>(sav);
            if (sa.id == 0)
            {
                //新增
                _ef.sys_admin.Add(sa);
                _ef.SaveChanges();
            }
            else
            {
                string pass = _ef.sys_admin.Where(x => x.id == sav.id).Select(x => x.admin_password).FirstOrDefault();
                //修改
                if (string.IsNullOrEmpty(sav.admin_password))
                {
                    sa.admin_password = pass;
                }
                _ef.sys_admin.Update(sa);
                _ef.SaveChanges();
            }
            return Content("success");
        }


        #endregion


        #region 角色管理



        public IActionResult GroupList(string Name, int Page = 1, int PageSize = 20)
        {
            IQueryable<sys_admin_group> q = _ef.sys_admin_group.Where(x => 1 == 1);
            if (!string.IsNullOrEmpty(Name))
            {
                q = q.Where(x => x.gname.Contains(Name));
            }
            int skip = (Page - 1) * PageSize;
            //_ef.sys_admin.ToList();
            //List<sys_adminVm> list =;
            ViewBag.Name = Name;
            PagerModel pm = new PagerModel();
            pm.Page = Page;
            pm.PageSize = PageSize;
            pm.Total = q.Count();
            pm.Data = Mapper.Map<List<sys_admin_group>, List<sys_admin_groupVm>>(q.Skip(skip).Take(PageSize).ToList());
            return View(pm);
        }


        [HttpPost]
        public IActionResult GroupDelete(string ids)
        {
            try
            {
                List<int> arr = ids.Split(',').Select(x => int.Parse(x)).ToList();
                foreach (int id in arr)
                {
                    sys_admin_group sa = _ef.sys_admin_group.FirstOrDefault(x => x.id == id);
                    if (sa != null)
                    {
                        _ef.sys_admin_group.Remove(sa);
                    }
                }
                _ef.SaveChanges();
                return Content("success");
            }
            catch (Exception ex)
            {
                return Content(ex.Message);
            }
        }



        public IActionResult GroupEdit(int id = 0)
        {
            sys_admin_groupVm sg = new sys_admin_groupVm();
            if (id != 0)
            {
                sys_admin_group sag = _ef.sys_admin_group.FirstOrDefault(x => x.id == id);
                sg = Mapper.Map<sys_admin_group, sys_admin_groupVm>(sag);
            }
            List<sys_admin_urlVm> lu = Mapper.Map<List<sys_admin_url>, List<sys_admin_urlVm>>(_ef.sys_admin_url.Where(x => x.url_status == 1).ToList());
            List<sys_admin_urlVm> plu = lu.Where(x => x.parent_id == 0).ToList();
            var list = GetMenus(plu, lu);
            ViewBag.Menus = GetMenuTable(list, true);
            return View(sg);
        }


        [HttpPost]
        public IActionResult GroupEditAction([ModelBinder(typeof(JsonBinder<sys_admin_groupVm>))]sys_admin_groupVm model)
        {
            sys_admin_group sg = Mapper.Map<sys_admin_groupVm, sys_admin_group>(model);
            if (model.id == 0)
            {
                _ef.sys_admin_group.Add(sg);
            }
            else
            {
                _ef.sys_admin_group.Update(sg);
            }
            _ef.SaveChanges();
            return Content("success");
        }





        #endregion



        #region 菜单管理

        public IActionResult MenuList()
        {
            List<sys_admin_urlVm> lu = Mapper.Map<List<sys_admin_url>, List<sys_admin_urlVm>>(_ef.sys_admin_url.Where(x => x.url_status == 1).ToList());
            List<sys_admin_urlVm> plu = lu.Where(x => x.parent_id == 0).ToList();
            PagerModel pm = new PagerModel();
            pm.Page = 0;
            pm.PageSize = 0;
            pm.Total = 0;
            var list = GetMenus(plu, lu);
            pm.Data = GetMenuTable(list,false);
            return View(pm);
        }


        [HttpPost]
        public IActionResult MenuDelete(string ids)
        {
            try
            {
                List<int> arr = ids.Split(',').Select(x => int.Parse(x)).ToList();
                foreach (int id in arr)
                {
                    sys_admin_url sa = _ef.sys_admin_url.FirstOrDefault(x => x.id == id);
                    if (sa != null)
                    {
                        _ef.sys_admin_url.Remove(sa);
                    }
                }
                _ef.SaveChanges();
                return Content("success");
            }
            catch (Exception ex)
            {
                return Content(ex.Message);
            }
        }


        public IActionResult MenuEdit(int id = 0)
        {

            sys_admin_urlVm sau = new sys_admin_urlVm();
            if (id != 0)
            {
                var sa = _ef.sys_admin_url.FirstOrDefault(x => x.id == id);
                if (sa != null)
                {
                    sau = Mapper.Map<sys_admin_url, sys_admin_urlVm>(sa);
                }
            }
            List<sys_admin_urlVm> lu = Mapper.Map<List<sys_admin_url>, List<sys_admin_urlVm>>(_ef.sys_admin_url.Where(x => x.url_status == 1).ToList());
            List<sys_admin_urlVm> plu = lu.Where(x => x.parent_id == 0).ToList();
            var list = GetMenus(plu, lu);
            ViewBag.UrlOptiong = GetMenuSelect(list, true);
            return View(sau);
        }

        [HttpPost]
        public IActionResult MenuEditAction([ModelBinder(typeof(JsonBinder<sys_admin_urlVm>))]sys_admin_urlVm model)
        {
            sys_admin_url sa = Mapper.Map<sys_admin_urlVm, sys_admin_url>(model);
            sa.url_status = 1;
            if (sa.id == 0)
            {
                _ef.sys_admin_url.Add(sa);
                _ef.SaveChanges();
            }
            else
            {
                _ef.sys_admin_url.Update(sa);
                _ef.SaveChanges();
            }
            return Content("success");
        }







        private List<sys_admin_url_itemVm> GetMenus(List<sys_admin_urlVm> plu, List<sys_admin_urlVm> lu)
        {
            List<sys_admin_url_itemVm> rs = new List<sys_admin_url_itemVm>();
            foreach (var item in plu)
            {
                sys_admin_url_itemVm temp = new sys_admin_url_itemVm();
                temp.id = item.id;
                temp.name = item.url_name;
                temp.url = item.url;
                temp.icon = "";
                temp.children = GetMenus(lu.Where(x => x.parent_id == item.id).ToList(), lu);
                rs.Add(temp);
            }
            return rs;
        }


        public string GetMenuTable(List<sys_admin_url_itemVm> Rs,bool IsShow)
        {
            StringBuilder sb = new StringBuilder();
            string tableTemplate = "<table class='layui-table' ><thead><tr><th><div class='layui-unselect header layui-form-checkbox' lay-skin='primary'>" +
                "<i class='layui-icon'>&#xe605;</i></div></th><th>ID</th><th>菜单名</th><th>菜单路径</th>";
            string trTemplate = "<tr><td><div class='layui-unselect layui-form-checkbox' lay-skin='primary' data-id='{0}'><i class='layui - icon'>&#xe605;</i></div>" +
                "</td><td>{0}</td><td>{1}</td><td>{2}</td>";
            if (!IsShow)
            {
                tableTemplate += "<th>操作</th>";
                trTemplate += "<td>{3}</td>";
            }
            tableTemplate += "</tr></thead><tbody>{0}</tbody></table>";
            trTemplate += "</tr>";

            string actionTemplate = "<a title='编辑' onclick=\"WeAdminShow('编辑', '" + Url.Action("MenuEdit") + "?id={0}')\" href='javascript:; '><i class='layui-icon'>&#xe642;</i></a>" +
                "<a title='删除' onclick=\"member_del(this, '{0}')\" href='javascript:; '><i class='layui-icon'>&#xe640;</i></a>";
            foreach (var item in Rs)
            {
                
                if (IsShow)
                {
                    sb.Append(string.Format(trTemplate, item.id, item.name, item.url));
                }
                else
                {
                    string action = string.Format(actionTemplate, item.id);
                    sb.Append(string.Format(trTemplate, item.id, item.name, item.url, action));
                }
                if (item.children.Count > 0)
                {
                    sb.Append(GetSubMenuTable(item.children, "&nbsp;&nbsp;|-&nbsp;",IsShow));
                }
            }
            return string.Format(tableTemplate, sb.ToString());
        }


        private string GetSubMenuTable(List<sys_admin_url_itemVm> Rs, string str,bool IsShow)
        {
            StringBuilder sb = new StringBuilder();
            string trTemplate = "<tr><td><div class='layui-unselect layui-form-checkbox' lay-skin='primary' data-id='{0}'><i class='layui - icon'>&#xe605;</i></div>" +
                "</td><td>{0}</td><td>{1}</td><td>{2}</td>";
            if (!IsShow)
            {
                trTemplate += "<td>{3}</td>";
            }
            trTemplate += "</tr>";

            string actionTemplate = "<a title='编辑' onclick=\"WeAdminShow('编辑', '" + Url.Action("MenuEdit") + "?id={0}')\" href='javascript:; '><i class='layui-icon'>&#xe642;</i></a>" +
                "<a title='删除' onclick=\"member_del(this, '{0}')\" href='javascript:; '><i class='layui-icon'>&#xe640;</i></a>";
            foreach (var item in Rs)
            {
                if (IsShow)
                {
                    sb.Append(string.Format(trTemplate, item.id, str+item.name, item.url));
                }
                else
                {
                    string action = string.Format(actionTemplate, item.id);
                    sb.Append(string.Format(trTemplate, item.id, str+ item.name, item.url, action));
                }
                if (item.children.Count > 0)
                {
                    sb.Append(GetSubMenuTable(item.children, str + "-&nbsp;",IsShow));
                }
            }
            return sb.ToString();
        }





        public string GetMenuSelect(List<sys_admin_url_itemVm> Rs, bool IsNull)
        {
            StringBuilder sb = new StringBuilder();
            string optionStr = "<option value='{0}' >{1}</option>";
            if (IsNull)
            {
                sb.Append(string.Format(optionStr, 0, "无"));
            }
            foreach (var item in Rs)
            {
                sb.Append(string.Format(optionStr, item.id, item.name));
                if (item.children.Count > 0)
                {
                    sb.Append(GetSubMenuSelect(item.children, " |- "));
                }
            }
            return sb.ToString();
        }


        public string GetSubMenuSelect(List<sys_admin_url_itemVm> Rs, string Str)
        {
            StringBuilder sb = new StringBuilder();
            string optionStr = "<option value='{0}' >{1}</option>";
            foreach (var item in Rs)
            {
                sb.Append(string.Format(optionStr, item.id, Str + item.name));
                if (item.children.Count > 0)
                {
                    sb.Append(GetSubMenuSelect(item.children, Str + "- "));
                }
            }
            return sb.ToString();
        }


        #endregion




        #region 左侧菜单


        public IActionResult MenuJson()
        {
            int id = int.Parse(HttpContext.User.FindFirstValue(SystemConst.CURRENT_ADMIN_ID));
            sys_admin sa =_ef.sys_admin.Where(x => x.id == id).FirstOrDefault();
            int gid = sa.admin_gid;
            string limits = _ef.sys_admin_group.Where(x => x.id == gid).Select(x => x.limits).FirstOrDefault();
            List<sys_admin_urlVm> lu = Mapper.Map<List<sys_admin_url>, List<sys_admin_urlVm>>(_ef.sys_admin_url.Where(x => x.url_status == 1 && (limits.Contains(x.id.ToString())||sa.admin_is_super)).ToList());
            List<sys_admin_urlVm> plu = lu.Where(x => x.parent_id == 0).ToList();
            var list = GetMenus(plu, lu);
            return Content(Newtonsoft.Json.JsonConvert.SerializeObject(new { status = 0, msg = "", data = list }));
        }


        private string GetMenuHtml(List<sys_admin_url_itemVm> Rs)
        {
            StringBuilder sb = new StringBuilder();
            string ulTemplate = "<ul class='nav' id='nav'>{0}</ul>";
            string liTemplate = "<li id='menu{0}'><a _href='{1}' ><i class='iconfont'>{2}</i><cite>{3}</cite><i class=‘iconfont nav_right’>&#xe697;</i></a></li>";
            foreach (var item in Rs)
            {
                sb.Append(string.Format(liTemplate, item.id, item.url, item.icon, item.url));
                if (item.children.Count > 0)
                {
                    sb.Append(GetSubMenus(item.children));
                }
            }
            return string.Format(ulTemplate, sb.ToString());
        }

        private string GetSubMenus(List<sys_admin_url_itemVm> Rs)
        {
            StringBuilder sb = new StringBuilder();
            string subTemplate = "<ul class='sub-menu' >{0}</ul>";
            string liTemplate = "<li id='menu{0}'><a _href='{1}' ><i class='iconfont'>&#xe697;</i><cite>{2}</cite></a></li>";
            foreach (var item in Rs)
            {
                sb.Append(string.Format(liTemplate, item.id, item.url, item.name));
                if (item.children.Count > 0)
                {
                    sb.Append(GetSubMenus(item.children));
                }
            }
            return string.Format(subTemplate, sb.ToString());
        }

        #endregion

        
    }
}